/**
 * 评论模块
 */


const mongoose = require('mongoose')
const Comment = mongoose.model('Comment')
const Article = mongoose.model('Article')
const { email, akismet } = require('../utils')

const addComment = async(ctx, next) => {
    // 可以添加一个验证码
    let id = ctx.params.id
    const body = ctx.request.body
    if (!body.content.trim()) {
        return ctx.body = {
            success: false,
            message: '评论不能为空'
        }
    }
    if (!body.name.trim()) {
        return ctx.body = {
            success: false,
            message: '评论用户不能为空',
        }
    }
    if (!body.email.trim()) {
        return ctx.body = {
            success: false,
            message: '用户邮箱不能为空',
        }
    }
    try {
        let result = await new Comment({
            ...body,
            article_id: id
        }).save()
        await Article.findByIdAndUpdate(id, {
            $inc: {
                comment_count: 1
            },
            $push: {
            	comment: result._id
            }
        })
        ctx.body = {
            success: true,
            message: '添加评论成功',
            data: {
            	id: result._id
            }
        }
    } catch (e) {
        ctx.throw(400, '创建评论失败')
    }

}

const deleteComment = async(ctx, next) => {
    const cid = ctx.params.cid
    try {
        const result = await Comment.findById(cid)
        if (!result) {
        	return ctx.body = {
        		success: false,
        		message: '没有该评论'
        	}
        }
       	await Comment.remove({_id: cid})
        //评论数-1
        const re = await Article.findByIdAndUpdate(result.article_id, { 
        	$inc: {
        		comment_count: -1
        	},
        	$pull: {
        		comment: cid
        	}
        })

        ctx.body = {
            success: true,
            message: '删除评论成功'
        }
    } catch (e) {
    	console.log(e)
        ctx.throw(400, '删除评论失败')
    }
}


const getCommentsList = async(ctx, next) => {

}

module.exports = {
    addComment,
    deleteComment,
    getCommentsList
}